import Base

# Represents every landsquares of the map, in order to load them in RAM
class LandSquares():
    
    
    # constructor
    def __init__(self, topLeft = 0, bottomRight = 9999):
        # height of the map
        self.height = 2
        # witdh of the map
        self.width = 2
        # database object for queries
        self.mysql = Base.Base()
        self.mysql.connect()
        # array of land squares
        self.arr = self.requestForLandSquares(topLeft, bottomRight)
        
        
    # get a certain portion of the map from the DB
    def requestForLandSquares(self, topLeft = 0, bottomRight = 9999):
        res = self.mysql.req("SELECT * FROM land WHERE x >= " + str(topLeft) + 
                                            " and x <= " + str(bottomRight) + 
                                            " and y >= " + str(topLeft) + 
                                            " and y <= " + str(bottomRight) + 
                                            " ORDER BY x ASC, y ASC;")
        a = []
        for row in res:
            a.append(row)
        return a
    
    
    # get a precise landsquare in the array
    def get(self, x, y):
        print x * self.width + y
        return self.arr[x * self.width + y]
    
    
    # get name of the landsquare
    def getName(self, row):
        return row[2]
    
    
    # get x of the landsquare
    def getX(self, row):
        return row[0]
        
    
    # get y of the landsquare
    def getY(self, row):
        return row[1]
        
    
    # the XML structure to output
    def formatXML(self):
        xml = '<landsquares width="' + str(self.width) + '" height="' + str(self.height) + '">'
        for l in self.arr:
            xml += '\n\t<landsquare>\n\t\t<name>' + self.getName(l) + '</name>\n\t\t<x>' + str(self.getX(l)) + '</x>\n\t\t<y>' + str(self.getY(l)) + '</y>\n\t</landsquare>';
        xml += '\n</lansquares>'
        return xml
        

l = LandSquares()
chaine = l.formatXML()
print l.formatXML()